package com.jqk.procuder.service.impl;

import com.jqk.procuder.entity.Order;
import com.jqk.procuder.entity.Product;
import com.jqk.procuder.entity.TransactionLog;
import com.jqk.procuder.repository.OrderRepository;
import com.jqk.procuder.repository.TransactionLogRepository;
import com.jqk.procuder.service.OrderService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;


/**
 * @Author:JiangQiKun
 * @Date:2022/03/20 10:25 PM
 * Description:
 * com.jqk.consumer.service.implOrderServiceImpl
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private OrderRepository orderBaseRepository;

    @Autowired
    private TransactionLogRepository transactionLogRepository;

    private static final String TOPIC = "order";


    /**
     * 执行本地事务时调用，将订单数据和事务日志写入本地数据库
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createOrder(Order order, String transactionId) {
        //1.创建订单
        //2.写入事务日志
        TransactionLog log = new TransactionLog();
        log.setId(transactionId);
        log.setBusiness("order");
        log.setForeignKey(String.valueOf(order.getId()));
        return orderBaseRepository.save(order) && transactionLogRepository.save(log);
    }

    /**
     * 前端调用，只用于向RocketMQ发送事务消息
     */
    @Override
    public void createOrder(Order order) {
        String transactionId = UUID.randomUUID().toString();
        order.setOrderNo("订单号");
        Product product = new Product();
        product.setProductCode(order.getProductCode());
        product.setAmount(order.getNumber());
        rocketMQTemplate.sendMessageInTransaction(TOPIC,
                MessageBuilder.withPayload(product)
                        .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                        .setHeader("body", order)
                        .build(), order);
    }
}
